#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <Hash.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include<Wire.h>
#include<LiquidCrystal_I2C.h>
#include<DHT11.h>

LiquidCrystal_I2C lcd(0x27,16,2);
DHT11 dht(D3);

#define GD 2500
#define SOIL_PIN A0
#define LIGHT_PIN A0

String temperature = "Temperature:37C";
String humidity = "Humidity:35%";
String soil_humidity = "SoilHumidity:35%";
String light = "Light:57%";

// Replace with your network credentials
//for more projects visit www.Blackkeyhole.com
const char* ssid = "agro";
const char* password = "12345678";
int lumi = 57;
int soil = 0;
int t = 0;
int h = 0;
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;  // will store last time DHT was updated

// Updates DHT readings every 10 seconds
const long interval = 10000;

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  <style>
    html {
     font-family: Arial;
     display: inline-block;
     margin: 0px auto;
     text-align: center;
    }
    h2 { font-size: 3.0rem; }
    p { font-size: 3.0rem; }
    .units { font-size: 1.2rem; }
    .dht-labels{
      font-size: 1.5rem;
      vertical-align:middle;
      padding-bottom: 15px;
    }
  </style>
</head>
<body>
  <h2>Электронный Агроном</h2>
  <p>
    <i class="fas fa-thermometer-half" style="color:#059e8a;"></i>
    <span class="dht-labels">Температура</span> 
    <span id="temperature">%TEMPERATURE%</span>
    <sup class="units">&deg;C</sup>
  </p>
  <p>
    <i class="fas fa-tint" style="color:#00add6;"></i> 
    <span class="dht-labels">Влажность</span>
    <span id="humidity">%HUMIDITY%</span>
    <sup class="units">%%</sup>
  </p>
  <p>
    <i class="fas fa-leaf" style="color:#008000;"></i> 
    <span class="dht-labels">Влажность почвы</span>
    <span id="soil">%SOIL%</span>
    <sup class="units">%%</sup>
</p>
    <p>
    <i class="fas fa-certificate" style="color:#FAC668;"></i> 
    <span class="dht-labels">Освещеность</span>
    <span id="limi">%LUMI%</span>
    <sup class="units">%%</sup>
</p>
</body>
<script>
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("temperature").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/temperature", true);
  xhttp.send();
}, 10000 ) ;
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("soil").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/soil", true);
  xhttp.send();
}, 10000 ) ;

setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("lumi").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/lumi", true);
  xhttp.send();
}, 10000 ) ;

setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("humidity").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/humidity", true);
  xhttp.send();
}, 10000 ) ;
</script>
</html>)rawliteral";

// Replaces placeholder with DHT values
String processor(const String& var) {
  //Serial.println(var);
  if (var == "TEMPERATURE") {
    return String(t);
  }
  if (var == "LUMI") {
    return String(lumi);
  }
  if (var == "SOIL") {
    return String(soil);
  } else if (var == "HUMIDITY") {
    return String(h);
  }
  return String();
}

void setup() {
  // Serial port for debugging purposes
  Serial.begin(9600);

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println(".");
  }

  // Print ESP8266 Local IP Address
  Serial.println(WiFi.localIP());

  // Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
    request->send_P(200, "text/html", index_html, processor);
  });
  server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest* request) {
    request->send_P(200, "text/plain", String(t).c_str());
  });
  server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest* request) {
    request->send_P(200, "text/plain", String(h).c_str());
  });

  // Start server
  server.begin();
}

void loop() {
    dht.readTemperatureHumidity(t, h);
  lcd.clear();

  //TEPERATURE
  lcd.setCursor(0, 0);
  temperature = "Temperature: " + String(t) + "C";
  lcd.print(temperature);
  Serial.println(temperature);

  //HUMIDITY
  lcd.setCursor(0, 1);
  humidity = "Humidity: " + String(h) + "%";
  lcd.print(humidity);
  Serial.println(humidity);

  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    // save the last time you updated the DHT values
    previousMillis = currentMillis;
  }

  delay(GD);
  lcd.clear();

  //SOIL HUMIDITY
  soil = map(analogRead(SOIL_PIN), 0, 1023, 0, 100);
  soil_humidity = "SoilHumidity:" + String(soil) + "%";
  lcd.setCursor(0, 0);
  lcd.print(soil_humidity);
  Serial.println(soil_humidity);

  //light
  if(lumi == 57 and (100 - map(analogRead(LIGHT_PIN), 0, 1023, 0, 100)) != 0){
    lumi = 100 - map(analogRead(LIGHT_PIN), 0, 1023, 0, 100);
    light = "Light:" + String(lumi) + "%";
  }
  lcd.setCursor(0, 1);
  lcd.print(light);
  Serial.println(light);

  currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    // save the last time you updated the DHT values
    previousMillis = currentMillis;
  }

  delay(GD);

}